package com.handong.handserialprogram.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;

import com.handong.handserialprogram.utils.AppCache;
import com.handong.handserialprogram.utils.CallBackUtil;
import com.handong.handserialprogram.utils.SPUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import zsoft.signala.hubs.HubConnection;
import zsoft.signala.hubs.HubInvokeCallback;
import zsoft.signala.hubs.HubOnDataCallback;
import zsoft.signala.hubs.IHubProxy;
import zsoft.signala.transport.StateBase;
import zsoft.signala.transport.longpolling.LongPollingTransport;


public class SignalRService extends Service
{
    private static final String TAG = SignalRService.class.getSimpleName();
    private HubConnection mHubConnection;
    private IHubProxy mHubProxy;
    public boolean IsRunning =false;

    public static final String serverUrl = "https://"+SPUtil.getStringValue(SPUtil.SERVER_IP)+":"+SPUtil.getIntValue(SPUtil.CHAT_PORT);//服务器地址

    public static final String SERVER_HUB_CHAT = "ServerHub";//与服务器那边的名称一致

    public void startSignalA() {
        if (mHubConnection != null){
            Subscribe();
            mHubConnection.Start();
            IsRunning=true;
         }
    }

    public void stopSignalA() {
        if (mHubConnection != null)
            mHubConnection.Stop();
        IsRunning=false;
    }
    public void Subscribe()
    {
        if (mHubConnection != null)
            mHubProxy.On("sendMessage", new HubOnDataCallback() //接收返回的数据
            {
                @Override
                public void OnReceived(JSONArray args)
                {
                    //Log.d("zqy", room+message);
                    if(onReceiveListener != null){
                        onReceiveListener.onReceive(args.optString(0),args.optString(1),args.optString(2));
                    }
                }
            });

        mHubProxy.On("joinRoom", new HubOnDataCallback() //接收返回的数据
        {
            @Override
            public void OnReceived(JSONArray args)
            {

            }
        });
        mHubProxy.On("getRoomUserList", new HubOnDataCallback() //接收返回的数据
        {
            @Override
            public void OnReceived(JSONArray args)
            {

            }
        });
        mHubProxy.On("removeRoom", new HubOnDataCallback() //接收返回的数据
        {
            @Override
            public void OnReceived(JSONArray args)
            {

            }
        });
        mHubProxy.On("getRoomlist", new HubOnDataCallback() //接收返回的数据
        {
            @Override
            public void OnReceived(JSONArray args)
            {

            }
        });
        mHubProxy.On("showMessage", new HubOnDataCallback() //接收返回的数据
        {
            @Override
            public void OnReceived(JSONArray args)
            {

            }
        });
    }
    /**
     * 更新进度的回调接口
     */
    private CallBackUtil.OnReceiveListener onReceiveListener;

    private CallBackUtil.OnReconnectedListener onReconnectedListener;
    private CallBackUtil.OnReconnectingListener onReconnectingListener;

    public void closeRoom(String roomName)
    {
        List<String> a = new ArrayList<String>();
        a.add(roomName);
        mHubProxy.Invoke( "closeRoom", a,new HubInvokeCallback() {
            @Override
            public void OnResult(boolean succeeded, String response) {
                Log.d(TAG, "Success");
            }

            @Override
            public void OnError(Exception ex) {
                Log.d(TAG, "Error: " + ex.getMessage());
            }
        });

    }



    public void joinRoom(String roomName,String userName)
    {
        List<String> a = new ArrayList<String>();
        a.add(roomName);
        a.add(userName);
        mHubProxy.Invoke( "joinRoom", a,new HubInvokeCallback() {
            @Override
            public void OnResult(boolean succeeded, String response) {
                Log.d(TAG, "Success");
            }

            @Override
            public void OnError(Exception ex) {
                Log.d(TAG, "Error: " + ex.getMessage());
            }
        });

    }

    public void createAndJoinRoom(String roomName,String userName)
    {
        List<String> a = new ArrayList<String>();

        a.add(roomName);
        a.add(userName);

        mHubProxy.Invoke( "createAndJoinRoom", a,new HubInvokeCallback() {
            @Override
            public void OnResult(boolean succeeded, String response) {
                Log.d(TAG, "Success");
            }

            @Override
            public void OnError(Exception ex) {
                Log.d(TAG, "Error: " + ex.getMessage());
            }
        });

    }

    public void DisConnected()
    {
        List<String> a = new ArrayList<String>();

        mHubProxy.Invoke( "disconnected", a,new HubInvokeCallback() {
            @Override
            public void OnResult(boolean succeeded, String response) {
                Log.d(TAG, "Success");
            }

            @Override
            public void OnError(Exception ex) {
                Log.d(TAG, "Error: " + ex.getMessage());
            }
        });

    }

    public void sendData(String room,String message)
    {

        List<String> a = new ArrayList<String>();
        a.add(room);
        //a.add(username);
        a.add(message);
        mHubProxy.Invoke( "sendMessage", a,new HubInvokeCallback() {
            @Override
            public void OnResult(boolean succeeded, String response) {
                Log.d(TAG, "Success");
            }

            @Override
            public void OnError(Exception ex) {
                Log.d(TAG, "Error: " + ex.getMessage());
            }
        });

    }

    /**
     * 注册回调接口的方法，供外部调用
     * @param onReceiveListener
     */
    public void setOnReceiveListener(CallBackUtil.OnReceiveListener onReceiveListener) {
        this.onReceiveListener = onReceiveListener;
    }

    /**
     * 注册回调接口的方法，供外部调用
     * @param onReconnectedListener
     */
    public void setOnReconnectedListener(CallBackUtil.OnReconnectedListener onReconnectedListener) {
        this.onReconnectedListener = onReconnectedListener;
    }

    /**
     * 注册回调接口的方法，供外部调用
     * @param onReconnectingListener
     */
    public void setOnReconnectingListener(CallBackUtil.OnReconnectingListener onReconnectingListener) {
        this.onReconnectingListener = onReconnectingListener;
    }


    public void startSignalR(final  Context context)
    {

        mHubConnection = new HubConnection(serverUrl,context, new LongPollingTransport())
        {
            @Override
            public void OnStateChanged(StateBase oldState, StateBase newState) {
                //tvStatus.setText(oldState.getState() + " -> " + newState.getState());

                switch(newState.getState())
                {
                    case Connected:
                        if(onReconnectingListener != null){
                            onReconnectingListener.onReconnecting();
                        }
                        Log.d(TAG, "OnStateChanged: 連接成功");
                        break;
                    case Disconnected:
                        if(onReconnectedListener != null){
                            onReconnectedListener.onReconnected();
                        }
                        if(IsRunning) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            AppCache.getSignalRService().startSignalR(context);
                        }
                        Log.d(TAG, "OnStateChanged: 連接失敗");
                        break;
                    case Connecting:
                        //DisConnected();
                        Log.d("syk", "正在连接!");
                        break;
                    case Reconnecting:
                        if(onReconnectingListener != null){
                            onReconnectingListener.onReconnecting();
                        }
                        Log.d("syk", "重新连接！");
                        break;
                    case Disconnecting:
                        Log.d("syk", "断开连接！");
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void OnError(Exception exception) {
                Log.d(TAG, "OnError: ", exception);
//                if(onReconnectedListener != null){
//                    onReconnectedListener.onReconnected();
//                }
                //Toast.makeText(MainActivity.this, "On error: " + exception.getMessage(), Toast.LENGTH_LONG).show();
            }

        };

        try {
            mHubProxy = mHubConnection.CreateHubProxy("serverHub");
        } catch (OperationApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (mHubConnection != null) {

            Log.i("hub", "初始化服务");


            startSignalA();
            Log.i("hub", "启动服务");


        } else {
            Log.i("CONNECET_FAIL", "CONNETION = NULL");

        }
    }

//    public static final String serverUrl = "https://10.1.200.26:44301";//服务器地址
//
//    public static final String SERVER_HUB_CHAT = "ServerHub";//与服务器那边的名称一致
//    public static final String SERVER_METHOD_SEND = "sendMessage";//服务器上面的方法
//    public static final  String SEVER_METHOD_CREATEROOM="createRoom";//创建房间
//    public static final String CLIENT_METHOD_RECEIVE = "sendPrivateMessage";//客户端这边的方法，服务器调用时需要根据这个来进行对应的调用
//
//    private static final String TAG = "SignalRService";
//    private static final String SHARED_PREFS = "shared_pref";
//    private HubConnection mHubConnection;
//    private IHubProxy mHubProxy;
//    private Handler mHandler; // to display Toast message
    private final IBinder mBinder = (IBinder) new LocalBinder();
//    private Timer Meitimer;
//    private int time;
//    private SharedPreferences sp;
//
//    /**
//     * 更新进度的回调接口
//     */
//    private CallBackUtil.OnReceiveListener onReceiveListener;
//
//    private CallBackUtil.OnReconnectedListener onReconnectedListener;
//    private CallBackUtil.OnReconnectingListener onReconnectingListener;
//
//
//    /**
//     * 注册回调接口的方法，供外部调用
//     * @param onReceiveListener
//     */
//    public void setOnReceiveListener(CallBackUtil.OnReceiveListener onReceiveListener) {
//        this.onReceiveListener = onReceiveListener;
//    }
//
//    /**
//     * 注册回调接口的方法，供外部调用
//     * @param onReconnectedListener
//     */
//    public void setOnReconnectedListener(CallBackUtil.OnReconnectedListener onReconnectedListener) {
//        this.onReconnectedListener = onReconnectedListener;
//    }
//
//    /**
//     * 注册回调接口的方法，供外部调用
//     * @param onReconnectingListener
//     */
//    public void setOnReconnectingListener(CallBackUtil.OnReconnectingListener onReconnectingListener) {
//        this.onReconnectingListener = onReconnectingListener;
//    }
//
//
//    @Override
//    public void onCreate()
//    {
//        super.onCreate();
//
//        Log.d(TAG, "Service Created");
//
//        sp = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
//        mHandler = new Handler(Looper.myLooper());
//    }
//
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId)
//    {
//
//        int result = super.onStartCommand(intent, flags, startId);
//        startSignalR(getApplicationContext());
//        return result;
//    }
//
    @Override
    public IBinder onBind(Intent intent)
    {
        //startSignalR(getApplicationContext());
        return mBinder;
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder
    {
        public SignalRService getService()
        {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }
//
//
//
//    /**
//     * 服务器通知客户端调用方法
//     */
////    private void serviceOpatorClient() {
////        mHubProxy.subscribe("sendPrivateMessage").addReceivedHandler(
////                new Action<JsonElement[]>() {
////
////                    @Override
////                    public void run(JsonElement[] obj)
////                            throws Exception {
////                        Log.i("hub", "ffffffff"+obj[0].toString()+"长度："+obj.length);
////                        Log.i("hub", "ffffffff"+obj[1].toString()+"长度："+obj.length);
////                        Log.i("hub", "ffffffff"+obj[2].toString()+"长度："+obj.length);
////                        Log.i("hub", "ffffffff"+obj[3].toString()+"长度："+obj.length);
////                        if (obj.length > 3) {
////                            String data = obj[2].toString();
////                            Log.i("hub", obj[2].toString());
////                        }
////
////                    }
////                });
////    }
//
////    /**
////     * 连接服务器超时
////     */
////    public void connectTimeout(){
////
////
////        Meitimer = new Timer();
////        TimerTask task = new TimerTask() {
////            @Override
////            public void run() {
////                try {
////                    if(mHubConnection != null){
////                        String token = mHubConnection.getConnectionToken();
////                        if (token != null) {
////                            Meitimer.cancel();
////                            time =0;
////                            return;
////                        }
////                    }
////                    if(time >0){
////                        Log.i("+++connectTimeout", "连接超时");
////                        time =0;
////                        Meitimer.cancel();
////                        return;
////                    }
////
////                    time= time+1;
////                } catch (Exception e) {
////                    // TODO: handle exception
////                }
////
////            }
////        };
////        Meitimer.scheduleAtFixedRate(task, 1000*20, 1000*20);
////    }
//
    @Override
    public void onDestroy()
    {
        stopSignalA();
        //mHubConnection.Stop();
        super.onDestroy();

    }
}